package com.tool.app.util.number;

import java.math.BigDecimal;

/**
 *
 */
public class BigDecimalUtils {
    public static final BigDecimal addSafely(BigDecimal a, BigDecimal b) {
        if (a == null && b == null) {
            return null;
        } else if (a == null) {
            return b;
        } else if (b == null) {
            return a;
        } else
            return a.add(b);
    }

    public static final BigDecimal addSubtract(BigDecimal a, BigDecimal b) {
        if (a == null && b == null) {
            return null;
        } else if (a == null) {
            return b;
        } else if (b == null) {
            return a;
        } else
            return a.subtract(b);
    }

    /**
     * 将Object类型转换成BigDecimal
     * @param object
     * @return
     */
    public static BigDecimal toBigDecimal(Object object) {
        if (object instanceof BigDecimal) {
            return (BigDecimal) object;
        } else if (object instanceof String) {
            return new BigDecimal((String) object);
        } else if (object instanceof Byte) {
            return new BigDecimal(((Byte) object).intValue());
        } else if (object instanceof Short) {
            return new BigDecimal(((Short) object).intValue());
        } else if (object instanceof Integer) {
            return new BigDecimal((Integer) object);
        } else if (object instanceof Long) {
            return new BigDecimal((Long) object);
        } else if (object instanceof Float) {
            return new BigDecimal(((Float) object).doubleValue());
        } else if (object instanceof Double) {
            return new BigDecimal((Double) object);
        } else if (object instanceof Number) {
            return new BigDecimal(((Number) object).doubleValue());
        } else if (object instanceof CharSequence) {
            return new BigDecimal(object.toString());
        }
        throw new IllegalArgumentException("Cannot convert Object to BigDecimal");
    }
}
